package com.xu.security.handler;

import com.alibaba.fastjson.JSONObject;
import com.xu.security.model.OnlineUser;
import com.xu.security.token.TokenService;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;

/**
 * 退出登录操作类
 *
 * @Author: 许乾伟
 * @Date: 2024/2/27 11:07
 */
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Resource
    TokenService tokenService;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        OnlineUser onlineUser = tokenService.getOnlineUser(request);
        if (onlineUser != null) {
            // 删除用户缓存记录
            tokenService.delLoginUser(onlineUser.getToken());
        }
        JSONObject result = new JSONObject();
        result.put("code",200);
        result.put("msg","成功");
        result.put("data","退出成功");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSONObject.toJSONString(result));
    }
}
